import os
import tempfile
import traceback
from typing import Any, Dict, Union

import config
from core.inference import inference_asr
from fastapi import APIRouter, File, HTTPException, UploadFile
from pydub import AudioSegment

from .schemas import ASRResponse, ErrorResponse, SuccessResponse

router = APIRouter()


@router.post("/transcriptions")
async def transcribe(
    file: UploadFile = File(...),
    model: str = "paraformer",
    response_format: str = "json",
) -> Union[Dict[str, Any], ErrorResponse]:
    if not file or not file.filename:
        return ErrorResponse(code=400, message="无效的文件", detail="未提供文件")

    if not file.filename.endswith(".wav"):
        return ErrorResponse(
            code=400, message="不支持的文件格式", detail="只支持 WAV 格式的音频文件"
        )

    temp_file_path = None
    try:
        # 创建临时文件
        with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_file:
            content = await file.read()
            temp_file.write(content)
            temp_file_path = temp_file.name

        # 处理音频文件
        audio = AudioSegment.from_file(temp_file_path)
        audio = audio.set_frame_rate(16000)  # 16kHz 采样率
        audio = audio.set_channels(1)  # 单声道
        audio = audio.set_sample_width(2)  # 设置采样深度为 16 位（2 字节）
        audio.export(temp_file_path, format="wav")

        # 调用语音识别服务
        result = inference_asr(temp_file_path, config.ASR_PIPELINE)
        return {"text": result[0].get("text", "")}

    except Exception as e:
        return ErrorResponse(
            code=500, message="处理失败", detail=f"处理音频文件时发生错误: {str(e)}"
        )
    finally:
        # 清理临时文件
        if temp_file_path and os.path.exists(temp_file_path):
            try:
                os.unlink(temp_file_path)
            except Exception as e:
                print(f"清理临时文件失败: {str(e)}")
